<!--  登录页面的 Vue 组件  -->
<template>
  <div class="container">

    <!--  顶部 Logo -->
    <div class="login-header d-flex justify-content-center">
      <a href="/onlinetool/#/" title="首页">
        <img class="" src="../../public/image/logo/logo.png" alt="">
      </a>
    </div>

    <!--  头部导航栏 -->
    <nav class="my-header text-center nav-fill w-75 align-items-center">
      <div class="nav nav-tabs" id="nav-tab" role="tablist">
        <a class="nav-item nav-link active" id="nav-home-tab" data-toggle="tab" href="#nav-home" role="tab"
           aria-controls="nav-home" aria-selected="true">登录</a>
        <a class="nav-item nav-link" id="nav-profile-tab" data-toggle="tab" href="#nav-profile" role="tab"
           aria-controls="nav-profile" aria-selected="false">注册</a>
      </div>
    </nav>

    <!--  内容主体区域  -->
    <div class="my-content tab-content border-top-0 bg-light w-75 align-items-center" id="nav-tabContent">
      <!--  登录表单  -->
      <div class="tab-pane fade show active" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
        <form class="pt-3">
          <div class="form-group row justify-content-center">
            <label class="col-sm-2 col-form-label text-left" for="exampleInputEmail1">手机号</label>
            <input type="number" v-model="loginPhoneNumber" class="col-sm-8 form-control pr-3" id="exampleInputEmail1" aria-describedby="emailHelp"
                   placeholder="请输入手机号" required>
          </div>
          <div class="form-group row justify-content-center">
            <label class="col-sm-2 col-form-label text-left" for="exampleInputPassword1">密码</label>
            <input type="password" v-model="loginPassword" class="col-sm-8 form-control pr-3" id="exampleInputPassword1" placeholder="请输入密码"
                   required>
          </div>

          <div class="form-group row justify-content-center">
            <label class="col-sm-2 col-form-label text-left" for="iamgeCode">图形验证码</label>
            <input type="text" v-model="imageCode" class="col-sm-6 form-control pr-3" id="iamgeCode" placeholder="请输入图形验证码"
                   required>
            <div class="col-sm-2">
              <img id="webImageTrue" class="my-code-image" src="../../public/image/LTCS.jpg" alt="">
            </div>
          </div>

          <div class="form-group row justify-content-center">
            <div class="form-check pl-5  text-left">
              <input type="checkbox" class="form-check-input" id="exampleCheck1">
              <label class="form-check-label" for="exampleCheck1">记住我</label>
            </div>
          </div>

          <div class="text-center mt-2">
            <button class="btn btn-primary btn-block" @click="login" type="button">登录</button>
          </div>

        </form>
      </div>

      <!--  注册表单 -->
      <div class="tab-pane fade" id="nav-profile" role="tabpanel" aria-labelledby="nav-profile-tab">
        <form class="pt-3">
          <div class="form-group row justify-content-center">
            <label class="col-sm-2 col-form-label text-left" for="registerUser">用户名：</label>
            <input type="text" v-model=userName class="col-sm-8 form-control pr-3" id="registerUser"
                   aria-describedby="emailHelp" placeholder="输入用户名" required>
          </div>
          <div class="form-group row justify-content-center">
            <label class="col-sm-2 col-form-label text-left" for="registerExampleInputPassword1">密码：</label>
            <input type="password" v-model=password class="col-sm-8 form-control pr-3"
                   id="registerExampleInputPassword1" placeholder="请输入密码" required>
          </div>
          <div class="form-group row justify-content-center">
            <label class="col-sm-2 col-form-label text-left" for="registerCode">手机号：</label>
            <div class="my-code-bar col-sm-8 row">
              <input type="text" v-model=phoneNumber class="col-sm-8 form-control pr-3 text-left" id="registerCode"
                     aria-describedby="emailHelp" placeholder="请输入手机号" required>
              <div class="ml-1">
                <button id="sendCode" class="btn btn-primary" @click="sendMessage">发送验证码</button>
              </div>
            </div>
          </div>
          <div class="form-group row justify-content-center">
            <label class="col-sm-2 col-form-label text-left" for="registerEmail">验证码：</label>
            <input type="text" v-model=messageCode class="col-sm-8 form-control pr-3" id="registerEmail"
                   aria-describedby="emailHelp" placeholder="请输入短信验证码" required>
          </div>
          <div class="row justify-content-center">
            <div class="form-check pl-5  text-left">
              <input type="checkbox" class="form-check-input" id="registerExampleCheck1" required>
              <label class="form-check-label" for="exampleCheck1">我已阅读同意《条款》</label>
            </div>
          </div>

          <div class="text-center mt-2">
            <button class="btn btn-primary btn-block" type="button" @click="register">注册</button>
          </div>
        </form>
      </div>
    </div>


  </div>
</template>

<script>


  export default {
    name: 'Login',
    data () {
      return {
        count: '发送验证码',
        timer: null,
        /*  登录时的图形验证码(用户输入的) */
        imageCode: "",
        /*  后端返回的   */
        backImageCode: "LTCS",
        imageUrl: "",
        /*                        这部分是注册表单用到的 */
        /*  用户名 */
        userName: '',
        /*  密码  */
        password: '',
        /*  电话号码  */
        phoneNumber: '',
        /*  短信验证码(用户输入的验证码) */
        messageCode: '',
        /*  从后端返回过来的验证码*/
        backCode: "",
        /*                        这部分是登录表单用到的 */
        loginPhoneNumber: "",
        loginPassword: "",
        base64Code: ""
      }
    },
    created () {
      // 初始化的时候得有一张图形验证码
      // this.changeImage();
    },
    mounted () {
      // this.changeImage();
    },
    methods: {
      /*  更换图形验证码(没有用到)   */
      async changeImage() {
        const result = await this.$http.get("http://116.62.157.224:8081/imagecode");
        console.log("login page");
        console.log(result);
        console.log(result);
        console.log(result);
        console.log(result);
        console.log(result);
        this.backImageCode = result.data.code;
        console.log("图形验证码为：" + this.backImageCode);
        this.base64Code = result.data.baseCode;
        // this.imageUrl = result.data.url;
        $("#webImageTrue").attr("src", "data:image/jpeg;base64," + this.base64Code);

      },
      /*  发送短信验证码   */
      async sendMessage () {
        // 设置 disabled 属性
        this.$('#sendCode').attr('disabled', true)

        const TIME_COUNT = 10

        this.count = TIME_COUNT
        //  使用箭头函数，这样就不用另外保存this
        /*
            添加一个定时器，实现按钮上的倒计时
            同时定义一个变量保存该定时器，方便在定时器里面清除定时器
        * */
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.$('#sendCode').text(this.count)
            console.log(this.count)
            this.count--
          } else {
            console.log("结束")
            this.$('#sendCode').attr('disabled', false)

            /*  从 data 里面获取定时器对象，然后清除该定时器   */
            clearInterval(this.timer);
            this.timer = null
            this.$('#sendCode').text("再次发送")
          }

        }, 1000)

        /*  利用 async 和 await 简化 promise 操作    */
        const result = await this.$http.get('http://116.62.157.224:8081/phonnemessage', {
          params: {
            phoneNumber: this.phoneNumber
          }
        })

        console.log(result);
        console.log(result.data.code);

        // 将后端返回过来的验证码进行保存
        this.backCode = result.data.code
        console.log("后端返回过来的验证码为：" + this.backCode);

        console.log(result)

      },
      /*  发起注册请求*/
      async register () {
        // 首先判断验证码是否输入正确
        if (this.messageCode !== this.backCode) {
          alert("验证码输入错误！");
          return ;
        }

        const result = await this.$http.post('http://116.62.157.224:8081/register', {
          myUserName: this.userName,
          myPassword: this.password,
          myPhoneNumber: this.phoneNumber,
          myMessageCode: this.messageCode
        })
        console.log(result)
        console.log(result.data)
        if (result.data.code === "200") {
          alert("注册成功，请进行登录操作");
          // 直接采用最原始的方法刷新页面，因为是全局刷新，所以可以使用这个方法
          window.location.reload();
          // 使用编程式路由导航跳到当前页，页面不会进行刷新
          // this.$router.push("/login");
        } else {
          alert("注册失败")
        }

      },
      /*  发起登录请求  */
      async login() {
        // 首先判断图形验证码是否输入正确
        if (this.imageCode !== this.backImageCode) {
          return alert("图形验证码输入错误");
        }

        const result = await this.$http.get("http://116.62.157.224:8081/login", {
          params: {
            phone: this.loginPhoneNumber,
            password: this.loginPassword
          }
        });
        console.log("result = " + result);

        // 后端服务器需要将 token 放进 result 里面并返回
        // 将获取到的 token 存入 sessionStorage 中
        window.sessionStorage.setItem("token", result.data.token);
        window.sessionStorage.setItem("username", result.data.username);

        /*  设置*/
        // var token =  window.sessionStorage.getItem("token");
        // console.log("token = " + token);

        console.log(result);
        console.log(result.data.code);
        if (result.data.code === "200") {
          alert("登录成功");
          this.$router.push("/")
        } else {
          alert("登录失败！请检查用户名密码");
        }
      }

    }
  }
</script>

<style scoped>

  .row {
    margin-left: 0;
    margin-right: 0;
  }

  .login-header {
    margin-top: 40px;
  }

  .my-header {
    margin: 60px auto 0 auto;
  }

  .my-content {
    margin: 0 auto;
  }

  .my-code-image {
    width: 100%;
    height: 100%;
    cursor: pointer;
  }

  .my-code-bar {
    padding-left: 0;
  }
</style>


